package top.zhangjianyong.blog.config.filter;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import top.zhangjianyong.blog.cache.UserCache;
import top.zhangjianyong.blog.enums.RespCode;
import top.zhangjianyong.blog.entity.po.User;
import top.zhangjianyong.blog.response.ApiResponse;

/**
 * 用户过滤器
 *
 * @author HDN
 * @since 2024/7/28 下午5:08
 */
@Slf4j
public class UserFilter implements Filter {

  private static final List<String> IGNORE_URI =
      Arrays.asList(
          "/common/sendVCode", "/user/login", "/user/password/reset", "/druid", "/portal");

  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException {
    log.info("用户过滤器。。。");
    try {
      HttpServletRequest request = (HttpServletRequest) servletRequest;
      String uri = request.getRequestURI();
      log.info("uri:{}", uri);
      if (IGNORE_URI.stream().noneMatch(uri::startsWith)) {
        User user = UserCache.user();
        if (user == null) {
          printResponse(ApiResponse.fail(RespCode.USER_NOT_LOGIN), servletResponse);
          return;
        }
      }

      filterChain.doFilter(servletRequest, servletResponse);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      printResponse(ApiResponse.fail(e.getMessage()), servletResponse);
    }
  }

  public void printResponse(ApiResponse apiResponse, ServletResponse response) throws IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().print(JSONObject.toJSONString(apiResponse));
  }
}
